package cc.verywell.pureblock.msg.nfs.linkmap;

import java.util.List;

import cc.verywell.pureblock.util.AutoClosed;

/**
* 
* Copyright © 2019 TanYaqiu. All rights reserved.
* @author TanYaqiu 
* @address flat 601
* @date 2019年6月19日 下午2:54:40
*/
public class EasyTablesSorted implements EasyTables,EasyTable {

	final AutoClosed ac;
	final List<EasyTableHDhead> files;
	public EasyTablesSorted(AutoClosed ac,List<EasyTableHDhead> readOnlyFiles) {
		this.ac = ac;
		this.files = readOnlyFiles;
	}
	
	@Override
	public EasyIteratorGroup get(EasyIteratorGroup group, LinkCell startWith) {
		EasyIterator it = get(startWith);
		if(it!=null && it.hasNext()) {
			if(group==null)group = new 	EasyIteratorGroup();
			group.add(it);
		}

		return group;
	}
	@Override
	public EasyIterator get(LinkCell startWith) {
		if(files.isEmpty())return null;
		int a = 0,b = files.size()-1;
		//EasyTableHDhead t = null;
		while(a<b) {
			int c = (a+b)>>1;
			EasyTableHDhead u = files.get(c);
			int h = u.between(startWith);
			if(h==0) {
				//t = u;// t checked.
				a = c;
				break;
			}else if(h>0 || u.start.startWith(startWith))
				b = c;
			else
				a = c+1;
		}
//		if(t==null) { // t unchecked.
//			t = files.get(a);
//			if(0!=t.startBetween(startWith))
//				return group;
//		}
		
		EasyIterator it = new SortedHDIterator(files, a, ac, startWith);
		return it.hasNext()?it:null;
	}
	
	static public class SortedHDIterator implements EasyIterator{

		final protected List<EasyTableHDhead> heads;
		final protected AutoClosed ac;
		final protected LinkCell startWith;
		protected int idx;
		protected EasyIterator current;
		public SortedHDIterator(List<EasyTableHDhead> heads, int idx, AutoClosed ac, LinkCell startWith) {
			this.heads = heads;
			this.ac = ac;
			this.startWith = startWith;
			this.idx = idx;
			next();
			
		}
		@Override
		public boolean hasNext() {
			return current!=null?current.hasNext():false;
		}
		@Override
		public LinkCell current() {
			return current!=null?current.current():null;
		}

		@Override
		public LinkCell next() {
			if(current!=null) {
				if(current.hasNext())
					return current.next();
				current = null;
				idx++;
			}
			while(idx<heads.size()) {
				EasyTableHDhead head = heads.get(idx);
				if(head.startBetween(startWith)==0) {
					EasyIterator it = heads.get(idx).getTable(ac).get(startWith);
					if(it!=null && it.hasNext()) {
						current = it;
						return it.next();
					}
				}else {
					break;
				}
				idx++;
			}
			return null;
		}

	}	

	
	
	
	
	
}
